﻿using System;
using System.Diagnostics;
using System.Linq;
using octalforty.Chinchillin.Shared.Deployment;
using octalforty.Chinchillin.Shared.Deployment.Metadata;

namespace octalforty.Chinchillin.Actions.Db
{
    [Action(Name)]
    public class RestoreDatabaseAction : ActionBase
    {
        #region Private Constants
        private const string Name = "restore-database";

        private static readonly ActionInfo actionInfo = new ActionInfo {
            Name = Name,
            Description = Resources.Db.RestoreDatabaseAction_Description,
            Arguments = new[] { 
                new ActionArgumentInfo("database", ActionArgumentType.Uri) { Description = Resources.Db.DatabaseAction_DatabaseArgumentDescription },
                new ActionArgumentInfo("backup-resource", ActionArgumentType.Uri) { Description = Resources.Db.DatabaseAction_DatabaseArgumentDescription }
            }
        };
        #endregion

        public IDbPlatformRegistry DbPlatformRegistry
        { get; set; }

        public RestoreDatabaseAction() :
            base(actionInfo)
        {
            
        }

        public override void Execute(IActionExecutionContext executionContext)
        {
            try
            {
                var database = (Uri)executionContext.Arguments["database"];
                var backupResource = ((Uri)executionContext.Arguments["backup-resource"]).AbsolutePath;

                var dbPlatform = DbPlatformRegistry.ResolveDbPlatform(database.Scheme) as IDbPlatformWithBackupSupport;
                if(dbPlatform == null)
                    throw new NotSupportedException(string.Format("Database backups are not supported for '{0}'", database.Scheme));

                var connectionInfo = dbPlatform.GetConnectionInfo(database);

                TracingManager.TraceEvent(executionContext, TraceEventType.Information, 0,
                    string.Format("Restoring Database '{0}' for platform '{1}' fron '{2}'", database.Segments.Last(), database.Scheme, backupResource));

                dbPlatform.RestoreDatabase(connectionInfo, backupResource);
            }
            catch(Exception e)
            {
                TracingManager.TraceEvent(executionContext, TraceEventType.Error, 0, e.ToString());
            }
        }
    }
}